package com.zcsy.manage.web.mall;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.PropertiesUtil;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.mall.CouponInfo;
import com.zcsy.manage.model.mall.GoodsCollection;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.model.mall.GoodsRead;
import com.zcsy.manage.model.mall.GoodsSpecification;
import com.zcsy.manage.model.mall.OrderInfo;
import com.zcsy.manage.model.mall.OwnerAddress;
import com.zcsy.manage.model.mall.ShoppingCart;
import com.zcsy.manage.model.mall.vo.CouponInfoVo;
import com.zcsy.manage.model.mall.vo.ShoppingCartVo;
import com.zcsy.manage.model.pay.weixin.PayOrderRequest;
import com.zcsy.manage.model.pay.weixin.PayOrderResultRequest;
import com.zcsy.manage.model.pay.weixin.PayOrderResultResponse;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.mall.ICouponDetailService;
import com.zcsy.manage.service.mall.ICouponInfoService;
import com.zcsy.manage.service.mall.IGoodsCollectionService;
import com.zcsy.manage.service.mall.IGoodsInfoService;
import com.zcsy.manage.service.mall.IGoodsReadService;
import com.zcsy.manage.service.mall.IGoodsSpecificationService;
import com.zcsy.manage.service.mall.IOrderInfoService;
import com.zcsy.manage.service.mall.IOwnerAddressService;
import com.zcsy.manage.service.mall.IShoppingCartService;
import com.zcsy.manage.service.quartz.ITimerTaskService;
import com.zcsy.manage.service.quartz.impl.TimerTaskServiceImpl;
import com.zcsy.manage.web.tools.WXPayUtils;

/**
 * 购物车controller
 * @Title: ShopcartController.java
 * @Package： com.zcsy.manage.web.mall 
 * @author hubing
 * @Copyright: 2016 武汉恒数利通软件有限公司 All rights reserved.
 * @date 2016年8月1日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/shopcart")
public class ShopcartController {

    @Autowired
    private IShoppingCartService shoopcartService;
    
    @Autowired
    private IOwnerAddressService ownerAddressService;
    
    @Autowired
    private ICellRegionService cellRegionService;
    
    @Autowired
    private ICouponDetailService couponService;
    
    @Autowired
    private IOrderInfoService orderInfoService;
    
    @Autowired
	private IGoodsReadService goodsReadService;
    
    @Autowired
    private IGoodsInfoService goodsService;
    
    @Autowired
    private IGoodsSpecificationService goodsSpecService;
    
    @Autowired
    private IGoodsCollectionService goodsCollectionService;
    
    @Autowired
    private ITimerTaskService timeTaskService;
    
    @Autowired
    private ICouponInfoService CouponInfoService;
    
    /**
     * 日志创建对象<br>
     */
    private static final Log logger = LogFactory.getLog(ShopcartController.class);
    
    
    /**
     * 查询购物车列表信息
     * @Method: shopcartList
     * @author hubing
     * @date 2016年8月1日
     */
    @RequestMapping(value="shopcartList", method = RequestMethod.GET)
    public String shopcartList(Model model, HttpServletRequest requst){
        User user = (User) requst.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = ((CellInfo) requst.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
                
        // 查询购物车信息
        List<ShoppingCart> cartList = shoopcartService.queryShoppingCart(user.getLoginname(), cellId);
//        List<ShoppingCart> cartList = shoopcartService.queryShoppingCart("ty1111", "100146010567114500");
        if (user != null) {
			List<GoodsRead> goodsReads = goodsReadService.getLatestGoodsReads(user.getLoginname());
			model.addAttribute("goodsReads", goodsReads);
		}
        // 转化页面视图显示
        List<ShoppingCartVo> shopcart = castShoopingCartVo(cartList);
        model.addAttribute("shopcart", shopcart);
        return "mall/shopcart";
    }
    
    /**
     * 
     * @Description 加入购物车<br>
     * 
     * @param goodsId 商品id
     * @param shopId 店铺id
     * @param goodsName 商品名称
     * @param logo 商品图片
     * @param price 商品价格
     * @param type 商品类型 1为正常商品
     * @param count 商品数量（加入购物车时指定为1）
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年8月12日
     * @see
     */
    @RequestMapping(value="addToCart", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson addToCart(String goodsId,String shopId,String goodsName,
    		String logo,BigDecimal price,Integer type,Integer count, String goodsSpecId, HttpServletRequest request,
            HttpServletResponse response){
    	RequestJson result = new RequestJson();
        try {
            User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            String cellId = ((CellInfo) request.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
//            
//        	ShoppingCart cart = new ShoppingCart();
//        	cart.setId(UniqueNumberUtils.get18UniqueNumber());
//        	cart.setGoodsId(goodsId);
//        	cart.setSpecificationId(goodsSpecId);
//        	cart.setShopId(shopId);
//        	cart.setGoodsName(goodsName);
//        	cart.setGoodsLogo(logo);
//        	cart.setPrice(price);
//        	cart.setType(type);
//        	cart.setAmount(count);
//        	cart.setCellId(cellId);
//        	cart.setUserAccount(user.getLoginname());
//        	shoopcartService.insertToCart(cart);
        	
            Map<String, Object> map = new HashMap<String, Object>();
            Object flag = Constants.SQL_RESULT_ERROR;

            //判断所选规格是否存在库存，若没有，给出提示并且退出
            GoodsSpecification spec = goodsSpecService.getGoodsSpecificationById(goodsSpecId);
            
            //若该商品没有规格，判断该商品是否有库存，若没有，给出提示并且退出
            GoodsInfo goods = goodsService.getGoodsInfoByPrimaryKey(goodsId);
            Integer userCartNum = shoopcartService.getUserCartNum(user.getLoginname());
            if (userCartNum >=  Constants.SHOPPING_CART_MAX_NUM) {
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("超出购物车添加商品上限50");
                result.setSuccess(false);
                return result;
            }
            
            if (spec != null) {
                if (spec.getStock() < count) {
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setMsg("该规格库存不足");
                    result.setSuccess(false);
                    return result;
                }
            }else{
                if (goods != null) {
                    if (goods.getState() != Constants.GOODS_SALE) {
                        result.setMsg("该商品已下架");
                        result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                        result.setSuccess(false);
                        return result;
                    }else{
                        if (goods.getStock() < count) {
                            result.setMsg("商品库存不足");
                            result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                            result.setSuccess(false);
                            return result;
                        }
                    }
                }else{
                    result.setMsg("该商品不存在");
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setSuccess(false);
                    return result;
                }
            }
            flag = shoopcartService.addToCart(user.getLoginname(), goodsId, goodsSpecId, count, OwnerConstants.CART_STATE_NORMAL, goods, spec, cellId);
            if (flag == (Object)OwnerConstants.NO_ENOUGH_GOODS) {
                result.setMsg("商品库存不足");
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setSuccess(false);
                return result;
            } else if (flag == (Object)Constants.SQL_RESULT_ERROR) {
                result.setMsg("添加失败");
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setSuccess(false);
                return result;
            } else {
                map.put("id", flag);
                result.setMsg("添加成功");
                result.setObj(map);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setSuccess(true);
                return result;
            }
            
        } catch (Exception e) {
        	e.printStackTrace();
        	logger.error("add my cart error:", e);
        	result.setMsg(RequestConstants.NET_ERROR);
        	result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * 添加我的收藏
     * @Method: addMyFavorite
     * @param param
     * @author hubing
     * @date 2016年8月1日
     */
    /**
     * @Description:添加判断，当该商品已未被收藏时才收藏
     * @author huangls 1449700087@qq.com
     * @date 2016年8月30日
     */
    @RequestMapping(value="addMyFavorite" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson addMyFavorite(String shopcartId, String goodsId, HttpServletRequest request,
            HttpServletResponse response) {
        RequestJson result = new RequestJson();
        try {
            User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            
            //根据用户id和商品id查询当前收藏
            GoodsCollection coodsCollection = goodsCollectionService.getGoodsCollectionByOwnerIdAndGoodsId(user.getId(), goodsId);
            
            //当该商品不在用户的收藏中时，将该商品收藏
            if(coodsCollection == null){
            	shoopcartService.addMyFavorite(shopcartId, goodsId, user.getId());
            	result.setMsg("收藏成功");
            } else {
            	result.setMsg("该商品您已收藏");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("add my favorite error:", e);
            result.setMsg(RequestConstants.NET_ERROR);
            result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * 删除购物车商品信息
     * @Method: delete
     * @param id 购物车记录id
     * @author hubing
     * @date 2016年8月1日
     */
    @RequestMapping(value="delete" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson delete(String id, HttpServletRequest request) {
        RequestJson result = new RequestJson();
        try {
            shoopcartService.deleteByPrimaryKey(id);
            result.setSuccess(true);
            result.setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("delete shopcart error:", e);
            result.setMsg(RequestConstants.NET_ERROR);
            result.setSuccess(false);
        }
        return result;
    }
    
    
    @RequestMapping(value="updateAmount" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson updateAmount(String id, String amount, String sub, String price, HttpServletRequest request,
            HttpServletResponse response) {
        RequestJson result = new RequestJson();
        try {
            shoopcartService.updateAmount(id, amount);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("update shopcart amount error:", e);
            result.setMsg(RequestConstants.NET_ERROR);
            result.setSuccess(false);
        }
        return result;
    }
    
    
   /**
    * 购买前校验商品库存信息
    * @Method: checkBuyBefore
    * @date 2016年9月20日
    */
    @RequestMapping(value="checkBuyBefore", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson checkBuyBefore(String shopcartIds, String goodsId,String shopId,
            String goodsName,String logo,BigDecimal price,Integer type,Integer count,
            String goodsSpecId, HttpServletRequest request){
        RequestJson result = new RequestJson();
        try {
            //判断所选规格是否存在库存，若没有，给出提示并且退出
            GoodsSpecification spec = goodsSpecService.getGoodsSpecificationById(goodsSpecId);
            
            //若该商品没有规格，判断该商品是否有库存，若没有，给出提示并且退出
            GoodsInfo goods = goodsService.getGoodsInfoByPrimaryKey(goodsId);
            if (spec != null) {
                if (spec.getStock() < count) {
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setMsg("该规格库存不足");
                    result.setSuccess(false);
                    return result;
                }
            }else{
                if (goods != null) {
                    if (goods.getState() != Constants.GOODS_SALE) {
                        result.setMsg("该商品已下架");
                        result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                        result.setSuccess(false);
                        return result;
                    }else{
                        if (goods.getStock() < count) {
                            result.setMsg("商品库存不足");
                            result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                            result.setSuccess(false);
                            return result;
                        }
                    }
                }else{
                    result.setMsg("该商品不存在");
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setSuccess(false);
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(RequestConstants.NET_ERROR);
            result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * 确认订单跳转界面
     * @Method: confirmOrder
     * @param shopcartIds 购物车记录id
     * @author hubing
     * @date 2016年8月2日
     */
    @RequestMapping(value="confirmOrder", method = RequestMethod.GET)
    public String confirmOrder(Model model,String shopcartIds, String goodsId,String shopId,
    		String goodsName,String logo,BigDecimal price,Integer type,Integer count,
    		String goodsSpecId, HttpServletRequest request) {

        String cellId = ((CellInfo) request.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String ownerId = user.getId();
        
        // 收获地址
        OwnerAddress ownerAddress = new OwnerAddress();
        ownerAddress.setOwnerId(ownerId);
        ownerAddress.setCellId(cellId);

        List<OwnerAddress> ownerAddressList = ownerAddressService.selectAddressByOwnerIdAndCellId(ownerAddress);
        //将电话号码中间四位隐藏起来
        String recepientPhone = null;
        for(int i=0; i<ownerAddressList.size(); i++){
            recepientPhone = ownerAddressList.get(i).getRecepientPhone();
            recepientPhone = recepientPhone.substring(0,recepientPhone.length()-(recepientPhone.substring(3)).length())+"****"+recepientPhone.substring(7);
            ownerAddressList.get(i).setRecepientPhone(recepientPhone);
        }
        
        model.addAttribute("addressList", ownerAddressList);
        
        if(StringUtil.isEmptyString(shopcartIds)){
//            ShoppingCart cart = new ShoppingCart();
//            cart.setId(UniqueNumberUtils.get18UniqueNumber());
//            cart.setGoodsId(goodsId);
//            if(!StringUtil.isEmptyString(goodsSpecId)) {
//                cart.setSpecificationId(goodsSpecId);
//                GoodsSpecification goodsSpec = goodsSpecService.getGoodsSpecById(goodsSpecId);
//                cart.setMemo(goodsSpec.getAttrValues());
//            }
//            cart.setShopId(shopId);
//            cart.setGoodsName(goodsName);
//            cart.setGoodsLogo(logo);
//            cart.setPrice(price);
//            cart.setType(type);
//            cart.setAmount(count);
//            shoopcartService.insertToCart(cart);
            GoodsSpecification spec = goodsSpecService.getGoodsSpecificationById(goodsSpecId);
            GoodsInfo goods = goodsService.getGoodsInfoByPrimaryKey(goodsId);
            Object result = shoopcartService.addToCart(user.getLoginname(), goodsId, goodsSpecId, count, OwnerConstants.CART_STATE_FROMBUY, goods, spec, cellId);
            shopcartIds = result.toString();
        } 
       
        List<ShoppingCart> cartList = shoopcartService.getSettleCarts(shopcartIds.split(","));
        List<ShoppingCartVo> shopcart = null ;
//        if(type == Constants.GOODS_TYPE_SECKILL){
//        	shopcart = shoopcartService.castShoopingCartVo(cartList, Constants.GOODS_TYPE_SECKILL);
//        }
//        if(type == Constants.GOODS_TYPE_CARDS){
//        	shopcart = shoopcartService.castShoopingCartVo(cartList, Constants.GOODS_TYPE_CARDS);
//        } 
//        if(type == Constants.GOODS_TYPE_NORMAL) {
//        	// 转化页面视图显示
//        	shopcart = shoopcartService.castShoopingCartVo(cartList, Constants.GOODS_TYPE_NORMAL);
//        	
//        }
        shopcart = shoopcartService.castShoopingCartVo(cartList, type);
        model.addAttribute("shopcart", shopcart);
        
        BigDecimal total = getTotal(shopcart);
        BigDecimal carriageTotal = BigDecimal.ZERO;
        BigDecimal derateTotal = BigDecimal.ZERO;
        StringBuilder shopIds = new StringBuilder();
        for(ShoppingCartVo vo : shopcart) {
            carriageTotal = carriageTotal.add(vo.getCarriage());
            derateTotal = derateTotal.add(vo.getDerateAmount());
            if(!StringUtil.isEmptyString(vo.getShopId())) {
            	if(StringUtil.isEmptyString(shopIds.toString())) {
            		shopIds.append(vo.getShopId());
            	} else {
            		shopIds.append(",").append(vo.getShopId());
            	}
            }
        }
        
        // 优惠券信息
        List<CouponInfoVo> couponList = couponService.getAvaliabelCoupon(total, shopcart, shopIds.toString(), user.getLoginname());
        
        model.addAttribute("total", total);
        model.addAttribute("carriageTotal", carriageTotal.subtract(derateTotal));
        model.addAttribute("realTotal", total.add(carriageTotal).subtract(derateTotal));
        model.addAttribute("shopcartIds", shopcartIds);
        model.addAttribute("type", type);
        model.addAttribute("couponList", couponList);
        return "mall/confirm_order";
    }
   
    /**
     * 提交生成订单
     * @Method: sumbitOrder
     * @param shopcartIds
     * @author hubing
     * @date 2016年8月2日
     */
    @RequestMapping(value="sumbitOrder" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson sumbitOrder(@RequestBody List<OrderInfo> orderInfo, String shopcartIds, Integer type, HttpServletRequest request, HttpServletResponse response) {
        RequestJson result = new RequestJson();
        try {
            User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            
            List<ShoppingCart> cartList = shoopcartService.getSettleCarts(shopcartIds.split(","));
            RequestJson req = shoopcartService.checkSubmitOrder(cartList, user);
            if(req != null){
                return req;
            }
           
            OrderInfo info = shoopcartService.confirmOrderFromShopcart(shopcartIds, user, orderInfo, type);
            
            if(BigDecimal.ZERO.compareTo(info.getFinalPrice()) >= 0) {
                result.setResultCode(OwnerConstants.ORDER_NOT_NEED_PAY);
                
            } else {
                //定时器，10分钟后未付款，订单取消
                timeTaskService.orderTimeTask(TimerTaskServiceImpl.TASK_NO_PAY, info.getId());
                
                result.setResultCode(OwnerConstants.ORDER_NEED_PAY);
                result.setObj(info.getOrderNumber());
            }
            
           
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("生成订单失败");
            e.printStackTrace();
        }
        
        return result;
    }
    
    
    @RequestMapping(value="wxPayComplete", method = RequestMethod.GET)
    public String wxPayComplete(HttpServletRequest request, HttpServletResponse response) {
        
        return "mall/pay_complete";
    }
    
    @RequestMapping("payCode")
    public void payCode(String orderNumber, HttpServletRequest request, HttpServletResponse response) {
        // 生成订单
//        orderId = UniqueNumberUtils.get18UniqueNumber();
        String ip = getIp(request);
        ip = request.getRemoteHost();
        try {
            PayOrderRequest payRequest = new PayOrderRequest();
            payRequest.setNonce_str(UniqueNumberUtils.get16UniqueNumber());
            payRequest.setBody(new String("DLife test pay".getBytes(), "UTF-8"));
            String totlaFee = "";
            if(PropertiesUtil.isCeshi()) {
                totlaFee = "1";
            } else {
                totlaFee = orderInfoService.selectByOrderNumber(orderNumber).getFinalPrice().toString();
            }
            payRequest.setOut_trade_no(orderNumber);
            payRequest.setTotal_fee(totlaFee);
            payRequest.setSpbill_create_ip(ip);
            payRequest.setNotify_url("l");
            
            String orderInfo = WXPayUtils.createWeixinPayRequset(payRequest);
            logger.info("request xml ==== " + orderInfo);
            String codeUrl = WXPayUtils.getSubmitOrderResponse(orderInfo);
            
            int width = 200;
            int height = 200;
            String format = "png";
            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, width, height, hints);
            OutputStream out = null;
            out = response.getOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, format, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        }
    }
    
    @RequestMapping(value="wxPayResult" , method = RequestMethod.GET)
    @ResponseBody
    public RequestJson wxPayResult(String orderNumber, HttpServletRequest request,
            HttpServletResponse response) {
        RequestJson result = new RequestJson();
        try {
            PayOrderResultRequest resultReq = new PayOrderResultRequest();
            resultReq.setOut_trade_no(orderNumber);
            String requestXml = WXPayUtils.createWXPayResultRequest(resultReq);
            PayOrderResultResponse payResult = WXPayUtils.getPayResult(requestXml);
            
            
            // 根据微信文档return_code 和result_code都为SUCCESS的时候才会返回code_url
            if(null != payResult) {
                if("SUCCESS".equals(payResult.getReturn_code()) && "SUCCESS".equals(payResult.getResult_code())){
                    logger.info("pay result ==== " + payResult.getTrade_state());
                    if("SUCCESS".equals(payResult.getTrade_state())){
                        orderInfoService.payOrder(orderNumber, payResult);
                    } else {
                        result.setMsg(payResult.getTrade_state_desc());
                        result.setSuccess(false);
                    }
                } else {
                    System.out.println("pay getErr_code_des ==== " + payResult.getErr_code_des());
                    result.setMsg(payResult.getErr_code_des()); 
                    result.setSuccess(false);
                }
            } else {
                result.setMsg("请求支付结果失败"); 
                result.setSuccess(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            result.setMsg(RequestConstants.NET_ERROR);
            result.setSuccess(false);
        }
        return result;
    }
    
    
   
    @RequestMapping(value="addAddress" , method = RequestMethod.GET)
    public String addAddress(Model model,String addressId, HttpServletRequest req){
        //获取到当前用户登陆时默认的小区id
        String cellId = ((CellInfo) req.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
        //获取当前登陆的用户的信息
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String ownerId = user.getId();
        
        OwnerAddress ownerAddress = new OwnerAddress();
        ownerAddress.setOwnerId(ownerId);
        ownerAddress.setCellId(cellId);
        ownerAddress.setId(addressId);
                
        model.addAttribute("cellRegions", cellRegionService.getCellRegionByCellId(cellId));
        
        return "mall/addAddress";
    }
    
    private List<ShoppingCartVo> castShoopingCartVo(List<ShoppingCart> cartList) {
        List<ShoppingCartVo> voList = new ArrayList<>();
        ShoppingCartVo vo = null;
        for(ShoppingCart cart : cartList) {
            boolean flag = true;
            for(ShoppingCartVo vl : voList) {
                if(cart.getShopId().equals(vl.getShopId())) {
                    vl.getGoodsList().add(cart);
                    flag = false;
                    break;
                }
            }
            if(flag) {
                vo = new ShoppingCartVo(cart);
                
                // 当前用户店铺优惠券
                
                
                voList.add(vo);
                
            }
        }
        return voList;
    }
    
    private BigDecimal getTotal(List<ShoppingCartVo> list) {
        BigDecimal result = BigDecimal.ZERO;
        for(ShoppingCartVo vo : list) {
            BigDecimal shopTotal = BigDecimal.ZERO;
            for(ShoppingCart cart : vo.getGoodsList()) {
                shopTotal = shopTotal.add(cart.getSubTotal());
            }
            result = result.add(shopTotal);
        }
        return result;
    }
    
    public static void main(String[] args) {
        try {
            ShopcartController controller = new ShopcartController();
//            String orderInfo = controller.createWeixinPayOrder(UniqueNumberUtils.get18UniqueNumber(), 
//                    "192.168.1.241");
//            System.out.println("orderInfo ==== " + orderInfo);
//            String result = controller.httpOrder(orderInfo);
//            System.out.println("result ==== " + result);
//            String requset = controller.createWXPayResultRequest(UniqueNumberUtils.get18UniqueNumber());
//            String result = controller.getPayResult(requset);
//            System.out.println("pay result is: " + result);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(!StringUtil.isEmptyString(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if((!StringUtil.isEmptyString(ip)) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
    
    /**
     * @Description:根据店铺id查询有效的优惠劵
     * @param shopId 店铺id 
     * @author huangls 1449700087@qq.com
     * @date 2016年9月18日
     */
    @RequestMapping(value="getCoupons" , method = RequestMethod.GET)
    public String getCoupons(Model model, String shopId, HttpServletRequest request){
    	try {
    		if(shopId != null){
    			List<CouponInfo> couponInfoList = CouponInfoService.getCouponInfo(shopId);
    			model.addAttribute("couponInfoList", couponInfoList);
    		}
    		
    	} catch (Exception e) {
            e.printStackTrace();
        }
        return "/mall/getCoupons";
    }
    
    /**
     * @Description:保存领取到的优惠劵
     * @param couponInfoIds 优惠券id字符串
     * @param request
     * @return 
     * @author huangls 1449700087@qq.com
     * @date 2016年9月19日
     */
    @RequestMapping(value="saveCoupon" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveCoupon( String couponInfoIds, HttpServletRequest request) {
        RequestJson result = new RequestJson();
        try {
            User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            String resultMsg = CouponInfoService.saveCoupons(couponInfoIds, user);
            result.setSuccess(true);
            result.setMsg(resultMsg);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("领取优惠劵失败");
            e.printStackTrace();
        }
        return result;
    }
}
